package com.hjq.demo.yuliao.fragment

import android.util.Log
import android.view.View
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.google.gson.Gson
import com.hjq.demo.R
import com.hjq.demo.app.vb.TitleBarVbFragment
import com.hjq.demo.databinding.FragmentMessageHomeMainBinding
import com.hjq.demo.http.model.HttpData
import com.hjq.demo.ryquick.custom.MyConversationProvider
import com.hjq.demo.utils.CommonSpaceItemDecoration
import com.hjq.demo.utils.CommonSpaceItemDecoration.LINEARLAYOUT
import com.hjq.demo.yuliao.MainActivity
import com.hjq.demo.yuliao.adapter.HomeMainConversationMessageAdapter
import com.hjq.demo.yuliao.adapter.HomeMainMessageAdapter
import com.hjq.demo.yuliao.api.GetSingleChatListApi
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallback
import com.hjq.toast.ToastUtils
import com.hjq.widget.layout.WrapRecyclerView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.rong.imkit.MessageInterceptor
import io.rong.imkit.RongIM
import io.rong.imkit.config.RongConfigCenter
import io.rong.imkit.conversationlist.ConversationListFragment
import io.rong.imkit.conversationlist.provider.PrivateConversationProvider
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.message.ImageMessage
import io.rong.message.TextMessage
import org.json.JSONObject


/**
 *
 * @author jiahe
 * 创建日期 2022/2/8
 * 描述 首页消息列表
 *
 */
class HomeMainMessageFragment : TitleBarVbFragment<MainActivity, FragmentMessageHomeMainBinding>(), OnRefreshListener,
    OnItemClickListener {

    companion object {

        fun newInstance(): HomeMainMessageFragment {
            return HomeMainMessageFragment()
        }
    }

    private val recyclerView: WrapRecyclerView? by lazy { findViewById(R.id.rv_status_list) }

    private var adapter: HomeMainMessageAdapter? = null
    private var adapterMessage: HomeMainConversationMessageAdapter? = null

    private var transaction: FragmentTransaction? = null

    override fun initView() {
        // 粉丝和关注
        adapter = HomeMainMessageAdapter()
        adapter?.setOnItemClickListener(this)
        recyclerView?.layoutManager = LinearLayoutManager(getAttachActivity())
        recyclerView?.addItemDecoration(
            CommonSpaceItemDecoration(
                resources.getDimension(R.dimen.dp_7).toInt(), true,
                LINEARLAYOUT
            )
        )
        recyclerView?.adapter = adapter

        // 会话列表
        adapterMessage = HomeMainConversationMessageAdapter()
        adapterMessage?.setOnItemClickListener { adapter, view, position -> }
        binding.rvConversationList.layoutManager = LinearLayoutManager(getAttachActivity())
        binding.rvConversationList.addItemDecoration(
            CommonSpaceItemDecoration(
                resources.getDimension(R.dimen.dp_7).toInt(), true,
                LINEARLAYOUT
            )
        )
        binding.rvConversationList.adapter = adapterMessage

        binding.rlStatusRefresh.setOnRefreshListener(this)

        // IMCenter.getInstance().setMessageInterceptor(MyMessageInterceptor())
        // RongIM.getInstance().setMessageInterceptor(MyMessageInterceptor())
        RongIM.getInstance().setMessageInterceptor(object : MessageInterceptor {
            override fun interceptReceivedMessage(
                message: Message?,
                left: Int,
                hasPackage: Boolean,
                offline: Boolean
            ): Boolean {
                return false
            }

            override fun interceptOnSendMessage(message: Message?): Boolean {
                return false
            }

            override fun interceptOnSentMessage(message: Message?): Boolean {
                var textmsg: TextMessage? = null
                if (message?.content is TextMessage) {
                    Log.e("===>111", textmsg?.content.toString())
                } else if (message?.content is ImageMessage) {

                }

                textmsg = message?.content as TextMessage?
                Log.e("===>222", textmsg?.content.toString())
                Log.e("===>", Gson().toJson(message))
                Log.e(
                    "===>", JSONObject(Gson().toJson(message).toString()).getJSONObject("content").getString
                        ("content")
                )
                return false
            }

        })

        val conversationType = Conversation.ConversationType.PRIVATE
        val targetId = "17"
        val objectName = "RC:TxtMsg"
        val oldestMessageId = -1
        val count = 20

        RongIM.getInstance().getHistoryMessages(conversationType, targetId, objectName, oldestMessageId, count,
            object : RongIMClient.ResultCallback<List<Message?>?>() {
                /**
                 * 成功时回调
                 * @param messages 获取的消息列表
                 */
                override fun onSuccess(messages: List<Message?>?) {
                }

                /**
                 * 错误时回调。
                 * @param e 错误码
                 */
                override fun onError(e: RongIMClient.ErrorCode) {}
            })

        // 获取会话模板管理器
        val providerManager = RongConfigCenter.conversationListConfig().providerManager;
        // 用自定义模板替换 SDK 原有模板
        providerManager.replaceProvider(PrivateConversationProvider::class.java,
            MyConversationProvider()
        )

        setOnClickListener(binding.dtvMessage, binding.dtvFans, binding.dtvAttention)
    }

    override fun initData() {
        getConvasitionList()

        // 聊天对话框列表
        val conversationListFragment = ConversationListFragment()
        val manager = childFragmentManager
        transaction = manager.beginTransaction();
        transaction?.replace(R.id.container, conversationListFragment);
        transaction?.commit();
    }

    override fun isStatusBarEnabled(): Boolean {
        return !super.isStatusBarEnabled()
    }

    override fun onClick(view: View) {
        super.onClick(view)
        if (view == binding.dtvMessage) {

            // 聊天对话框列表
            val conversationListFragment = ConversationListFragment()
            val manager = childFragmentManager
            // val transaction = manager.beginTransaction();
            if (transaction?.isEmpty == true) {
                transaction?.replace(R.id.container, conversationListFragment);
                transaction?.commit()
            }

            binding.rvStatusList.visibility = View.GONE
            binding.container.visibility = View.VISIBLE

        } else if (view == binding.dtvFans) {
            binding.rvStatusList.visibility = View.VISIBLE
            binding.container.visibility = View.GONE
            getListData(true)
        } else if (view == binding.dtvAttention) {
            binding.rvStatusList.visibility = View.VISIBLE
            binding.container.visibility = View.GONE
            getListData(true)
        }
    }

    /**
     * [OnRefreshLoadMoreListener]
     */
    override fun onRefresh(refreshLayout: RefreshLayout) {
        getListData(true)
        postDelayed({
            binding.rlStatusRefresh.finishRefresh()
        }, 1000)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        getListData(false)
    }

    private fun getListData(isRefresh: Boolean) {
        val list = mutableListOf<String>()
        list.add("123456")
        list.add("123456")
        list.add("123456")
        list.add("123456")
        list.add("123456")
        list.add("123456")
        adapter?.setNewInstance(list)
    }

    private fun getConvasitionList() {
        EasyHttp.post(this)
            .api(GetSingleChatListApi())
            .request(object : HttpCallback<HttpData<GetSingleChatListApi.Bean>>(this) {
                override fun onSucceed(result: HttpData<GetSingleChatListApi.Bean>?) {

                }
            })
    }

    class MyMessageInterceptor : MessageInterceptor {

        override fun interceptReceivedMessage(
            message: Message?,
            left: Int,
            hasPackage: Boolean,
            offline: Boolean
        ): Boolean {

            ToastUtils.show("收到消息，准备拦截")
            return false
        }

        /**
         * 准备发送的回调
         */
        override fun interceptOnSendMessage(message: Message?): Boolean {
            return false
        }

        /**
         * 发送成功后的回调
         */
        override fun interceptOnSentMessage(message: Message?): Boolean {
            ToastUtils.show("发送成功后被我拦截")
            Log.e("===>", Gson().toJson(message))
//            EasyHttp.post(ApplicationLifecycle())
//                .tag("message")
//                .api(SendSingleChatMessageApi().apply {
//                    this.msg = message?.content
//                    this.msg_type = message?.conversationType.toString()
//                    this.receive_user_id = message?.targetId.toString()
//                })
//                .request(object : OnHttpListener<HttpData<Any>> {
//                    override fun onSucceed(result: HttpData<Any>?) {
//
//                    }
//
//                    override fun onFail(e: Exception?) {
//
//                    }
//
//                })
            return false
        }
    }

    override fun onDestroy() {
        super.onDestroy()

    }

    override fun onPause() {
        super.onPause()
        EasyHttp.cancel("message")
    }

}